<template>
  <div class="loginLayout">
    <el-form
      v-if="isLogin"
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="学号" prop="username">
        <el-input v-model="ruleForm.username" placeholder="学号" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="ruleForm.password"
          type="password"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPass">
        <el-input
          v-model="ruleForm.checkPass"
          type="password"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model.number="ruleForm.nickname" />
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="ruleForm.sex" placeholder="男">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >注册</el-button
        >
        <el-button @click="resetForm(ruleFormRef)">重新填写</el-button>
      </el-form-item>
      <p class="login" @click="() => (isLogin = false)">已有帐号?去登陆</p>
    </el-form>
    <el-form
      v-else
      ref="loginRuleFormRef"
      :model="loginRuleForm"
      status-icon
      :rules="loginRules"
      label-width="120px"
    >
      <el-form-item label="学号" prop="loginUsername">
        <el-input v-model="loginRuleForm.loginUsername" placeholder="学号" />
      </el-form-item>
      <el-form-item label="密码" prop="loginPassword">
        <el-input
          v-model="loginRuleForm.loginPassword"
          type="password"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="loginSubmitForm(loginRuleFormRef)"
          >登陆</el-button
        >
      </el-form-item>
      <p class="login" @click="() => (isLogin = true)">没有帐号?去注册</p>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import type { FormInstance } from "element-plus";
import { ElNotification } from "element-plus";
import { getUserMsg, applyUserMsg } from "@/api/user";
const loginRuleFormRef = ref<FormInstance>();
const ruleFormRef = ref<FormInstance>();
const isLogin = ref(false);
const checkLoginUsername = (rule: any, value: any, callback: any) => {
  if (!value || !value.trim()) {
    return callback(new Error("请填写学号"));
  }
  callback();
};

const checkLoginPassword = (rule: any, value: any, callback: any) => {
  if (value.trim() === "") {
    callback(new Error("请填写密码"));
  }
  callback();
};

const checkNicename = (rule: any, value: any, callback: any) => {
  if (!value || !value.trim()) {
    return callback(new Error("请填写名字"));
  }
  callback();
};

const checkUsername = (rule: any, value: any, callback: any) => {
  if (!value || !value.trim()) {
    return callback(new Error("请填写学号"));
  }
  callback();
};

const validatePass = (rule: any, value: any, callback: any) => {
  if (value.trim() === "") {
    callback(new Error("请填写密码"));
  } else {
    if (ruleForm.checkPass !== "") {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField("checkPass", () => null);
    }
    callback();
  }
};
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value.trim() === "") {
    callback(new Error("请再次填写密码"));
  } else if (value !== ruleForm.password) {
    callback(new Error("两次密码不一致"));
  } else {
    callback();
  }
};

const loginRuleForm = reactive({
  loginPassword: "",
  loginUsername: "",
});

const loginRules = reactive({
  loginUsername: [{ validator: checkLoginUsername, trigger: "blur" }],
  loginPassword: [{ validator: checkLoginPassword, trigger: "blur" }],
});

const ruleForm = reactive({
  password: "",
  checkPass: "",
  nickname: "",
  sex: "",
  username: "",
});

const rules = reactive({
  username: [{ validator: checkUsername, trigger: "blur" }],
  pass: [{ validator: validatePass, trigger: "blur" }],
  checkPass: [{ validator: validatePass2, trigger: "blur" }],
  nickname: [{ validator: checkNicename, trigger: "blur" }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await applyUserMsg({
        username: ruleForm.username.trim(),
        password: ruleForm.password.trim(),
        sex: ruleForm.sex,
        nickname: ruleForm.nickname.trim(),
      })
        .then((res) => {
          console.log(res);
          if (res.status === 200) {
            isLogin.value = false;
            ElNotification({
              title: "Success",
              message: res.msg,
              type: "success",
            });
          }
        })
        .catch((err:any) => {
          console.log(err);
           ElNotification({
              title: "error",
              message: err.message,
              type: "error",
            });
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const loginSubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      getUserMsg({
        username: loginRuleForm.loginUsername.trim(),
        password: loginRuleForm.loginPassword.trim(),
      }).then((res) => {
        console.log(res.res.username, loginRuleForm.loginUsername.trim(), res);
        if (res.res.username === loginRuleForm.loginUsername.trim()) {
          localStorage.setItem("userMsg", JSON.stringify(res.res));
          localStorage.setItem("__login_token__", JSON.stringify(res.token));
          ElNotification({
            title: "Success",
            message: "一秒后将跳转",
            type: "success",
          });
          setTimeout(() => {
            location.reload();
          }, 1200);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
</script>

<style lang="less">
.loginLayout {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  opacity: 0.8;
  position: relative;
  background-image: url(../public/loginbackgrounp.webp);
  background-size: 100% 100%;
  background-repeat: no-repeat;
  /deep/ .el-form {
    width: 100%;
    height: 100%;
    color: black;
    opacity: 1;
    /deep/ .el-form-item {
      color: black;
    }
  }
}
.el-form-item__label {
  color: black !important;
  width: 80px !important;
  flex-shrink: 0;
}
.el-form-item__error {
  color: yellow !important;
}
.login {
  color: red;
}
</style>